<template>
  <basic-container>
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #search>
        <div class="addQuestion">
          <el-popover placement="bottom" trigger="click" :width="250">
            <div class="flex">
              <el-button
                type="warning"
                size="small"
                v-for="item in website.questionType"
                :key="item.value"
                @click="showQuestion(item)"
                >{{ item.label }}
              </el-button>
            </div>
            <template #reference>
              <el-button type="primary" class="btn">添加</el-button>
            </template>
          </el-popover>
          <el-upload class="uploads" :before-upload="beforeUpload">
            <el-button type="primary" class="upload-btn">导入</el-button>
          </el-upload>
        </div>
      </template>
      <template #title="scoped">
        <div v-html="scoped.row.title" style="height: 24px; box-sizing: border-box;"></div>
      </template>
      <template #menu="scoped">
        <el-button type="primary" link icon="View" @click="beforeOpen(scoped, 0)">查看</el-button>
        <el-button type="primary" link icon="Edit" @click="beforeOpen(scoped, 1)">编辑</el-button>
        <el-button type="primary" link icon="Delete" @click="rowDel(scoped)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog v-model="dialogVisible" :title="formdata.label" center :fullscreen="true">
      <Filling
        v-if="formdata.type == '31'"
        :form="formdata"
        :rules="rules"
        :updateId="updateId"
        @addQuestions="addQuestions"
        @openView="questionShowDialog = true"
        @updateQuestions="updateQuestions"
      />
      <Multiple
        v-else-if="formdata.type == '22'"
        :form="formdata"
        :rules="rules"
        :updateId="updateId"
        @addQuestions="addQuestions"
        @openView="questionShowDialog = true"
        @updateQuestions="updateQuestions"
      />
      <Short
        v-else-if="formdata.type == '32'"
        :form="formdata"
        :rules="rules"
        :updateId="updateId"
        @addQuestions="addQuestions"
        @openView="questionShowDialog = true"
        @updateQuestions="updateQuestions"
      />
      <Single
        v-else-if="formdata.type == '21'"
        :form="formdata"
        :rules="rules"
        :updateId="updateId"
        @addQuestions="addQuestions"
        @openView="questionShowDialog = true"
        @updateQuestions="updateQuestions"
      />
      <TrueFalse
        v-else-if="formdata.type == '11'"
        :form="formdata"
        :rules="rules"
        :updateId="updateId"
        @addQuestions="addQuestions"
        @openView="questionShowDialog = true"
        @updateQuestions="updateQuestions"
      />
    </el-dialog>
    <el-dialog v-model="questionShowDialog" center :fullscreen="true" title="查看">
      <QuestionShow :question="formdata" />
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getQuestionList,
  getQuestionDetail,
  updateQuestions,
  removeQuestion,
  uploadQuestion,
} from '@/api/position/courseware';
import { addQuestion } from '@/api/question/index';
import QuestionShow from './components/Show.vue';

import option from '@/option/position/courseware';
import Filling from './edit/gap-filling.vue';
import Multiple from './edit/multiple-choice.vue';
import Short from './edit/short-answer.vue';
import Single from './edit/single-choice.vue';
import TrueFalse from './edit/true-false.vue';
import website from '@/config/website';

export default {
  components: {
    Filling,
    Multiple,
    Short,
    Single,
    TrueFalse,
    QuestionShow,
  },
  data() {
    return {
      form: {},
      formdata: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option,
      data: [],
      dialogVisible: false,
      questionShowDialog: false,
      rules: {
        level: [{ required: true, message: '请选择分类', trigger: 'change' }],
        title: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案', trigger: 'blur' }],
        score: [{ required: true, message: '请输入分数', trigger: 'blur' }],
      },
      updateId: '',
      question: {},
    };
  },
  created() {
    this.option.column[1].dicData = this.website.knowledgeLevelLists;
    this.option.column[2].dicData = this.website.questionType;
    this.option.column[9].dicData = this.website.securityLists;
    let question = sessionStorage.getItem('question');
    if (question) {
      question = JSON.parse(question);
      this.form.level = question.type;
      this.search.level = question.type;
      this.question = question;
    }
  },
  computed: {
    permissionList() {
      return {
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        editBtn: true,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    addQuestions(form) {
      const base = JSON.parse(JSON.stringify(form));
      const formdata = new FormData();
      const content = {};
      base.content.forEach(c => {
        content[c.prefix] = c.content;
      });
      base.contentMap = content;
      base.content = JSON.stringify(content);
      delete base.label;
      for (let key in base) {
        formdata.append(key, encodeURIComponent(base[key]));
      }
      formdata.append('knowledgeId', this.question.id || -1);
      console.log('add', base);

      addQuestion(formdata)
        .then(res => {
          this.$message.success('操作成功');
          this.onLoad(this.page, this.form);
          this.dialogVisible = false;
        })
        .catch(err => {
          this.$message.error('操作失败');
        });
    },
    updateQuestions(form) {
      const base = JSON.parse(JSON.stringify(form));
      const formdata = new FormData();
      const content = {};
      base.content.forEach(c => {
        content[c.prefix] = c.content;
      });
      base.contentMap = content;
      base.content = JSON.stringify(content);
      delete base.label;
      for (let key in base) {
        formdata.append(key, encodeURIComponent(base[key]));
      }
      formdata.append('id', this.updateId);
      formdata.append('knowledgeId', this.question.id || -1);
      console.log('update', base);
      updateQuestions(formdata)
        .then(res => {
          this.$message.success('操作成功');
          this.onLoad(this.page, this.form);
          this.dialogVisible = false;
        })
        .catch(err => {
          this.$message.error('操作失败');
        });
    },
    rowDel({ row }) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeQuestion(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    beforeOpen({ row }, type) {
      getQuestionDetail(row.id).then(res => {
        this.formatForm(res.data.data, true);
        if (type) {
          this.dialogVisible = true;
          this.updateId = row.id;
        } else {
          this.questionShowDialog = true;
        }
      });
    },
    searchReset() {
      this.form = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.form = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.form);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.question.id) {
        this.form.knowledgeId = this.question.id;
      }
      // if (this.form.id) {
      //   this.form.knowledgeId = this.form.id;
      // }
      if (this.form.level) {
        this.form.level = Number(this.form.level);
      }
      getQuestionList(page.currentPage, page.pageSize, this.form).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map(item => {
          const type = this.website.questionType.find(types => types.value == item.type);
          return {
            ...item,
            title: decodeURIComponent(item.title),
            type: type ? type.label : type,
          };
        });
        console.log('data', this.data);
        this.loading = false;
        this.selectionClear();
      });
      this.updateId = '';
    },
    showQuestion(data) {
      this.formatForm(data, false);
      this.dialogVisible = true;
    },
    formatForm(data, type) {
      switch (data.value) {
        case '21':
          // 单选
          this.formdata = {
            type: '21',
            level: this.question.type || '100',
            title: '',
            content: [
              { prefix: 'A', content: '' },
              { prefix: 'B', content: '' },
              { prefix: 'C', content: '' },
              { prefix: 'D', content: '' },
            ],
            analysis: '',
            answer: '',
            score: 0,
            label: data.label,
          };
          break;
        case '11':
          // 判断
          this.formdata = {
            type: '11',
            level: this.question.type || '100',
            title: '',
            content: [
              { prefix: 'A', content: '对' },
              { prefix: 'B', content: '错' },
            ],
            analysis: '',
            answer: '',
            score: 0,
            label: data.label,
          };
          break;
        case '22':
          // 多选
          this.formdata = {
            type: '22',
            level: this.question.type || '100',
            title: '',
            content: [
              { prefix: 'A', content: '' },
              { prefix: 'B', content: '' },
              { prefix: 'C', content: '' },
              { prefix: 'D', content: '' },
            ],
            analysis: '',
            answer: [],
            score: 0,
            label: data.label,
          };
          break;
        case '31':
          // 填空
          this.formdata = {
            type: '31',
            level: this.question.type || '100',
            title: '',
            content: [],
            analysis: '',
            answer: '',
            score: 0,
            label: data.label,
          };
          break;
        case '32':
          // 简答
          this.formdata = {
            type: '32',
            level: this.question.type || '100',
            title: '',
            content: [],
            analysis: '',
            answer: '',
            score: 0,
            label: data.label,
          };
          break;
      }
      if (!type) {
        return;
      }
      if (data.type) {
        this.formdata.type = String(data.type);
      }
      if (data.level) {
        const level = this.website.knowledgeLevelLists.find(item => item.label == data.level);
        if (level) {
          this.formdata.level = level.value;
        } else {
          this.formdata.level = String(data.level);
        }
      }
      if (data.title) {
        this.formdata.title = decodeURIComponent(data.title);
      }
      if (data.content) {
        const contentObj = JSON.parse(decodeURIComponent(data.content));
        const content = [];
        for (let key in contentObj) {
          content.push({
            prefix: key,
            content: contentObj[key],
          });
        }
        this.formdata.content = content;
        // if (data.content.includes('prefix')) {
        //   this.formdata.content = JSON.parse(decodeURIComponent(data.content)).filter(
        //     item => item.content != 'null'
        //   );
        // } else {
        //   const arr = data.content.split(',');
        //   this.formdata.content = arr
        //     .map((item, index) => {
        //       return {
        //         prefix: String.fromCharCode(index + 97).toUpperCase(),
        //         content: item,
        //       };
        //     })
        //     .filter(item => item.content != 'null');
        // }
      }
      if (data.analysis) {
        this.formdata.analysis = decodeURIComponent(data.analysis);
      }
      if (data.answer) {
        data.answer = decodeURIComponent(data.answer);
        console.log('this.formdata.answer', data.answer);
        if (data.type == '22') {
          this.formdata.answer = data.answer
            .split('')
            .join(',')
            .split(',')
            .filter(item => item);
        } else {
          this.formdata.answer = String(data.answer);
        }
      }
      if (data.score) {
        this.formdata.score = data.score;
      }
      if (data.security) {
        this.formdata.security = String(data.security);
      }
    },
    beforeUpload(file) {
      const formdata = new FormData();
      formdata.append('file', file);
      uploadQuestion(formdata).then(res => {
        this.$message.success('导入成功');
        this.onLoad(this.page, this.form);
      });
      return false;
    },
  },
};
</script>

<style scoped lang="scss">
.addQuestion {
  position: relative;

  .btn {
    position: absolute;
    top: 60px;
    right: 0;
    z-index: 10;
  }
}

.uploads {
  position: absolute;
  top: 60px;
  right: 80px;
  z-index: 10;

  .upload-btn {
    display: flex;
    justify-content: center;
    padding: 0;
    text-align: center;
    width: 60px;
  }
}

:deep(.cell p) {
  margin: 0 !important;
}
</style>
